package com.example.eureka.service.employee.service;

import com.example.eureka.service.employee.domain.Department;
import com.example.eureka.service.employee.domain.Employee;
import com.example.eureka.service.employee.mapper.EmployeeMapper;
import com.example.eureka.service.employee.utility.ResultMessage;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @SneakyThrows
    public Employee getEmployee(Long id) {
        Employee employee = employeeMapper.selectByPrimaryKey(id);

        String url = "http://127.0.0.1:8080/departments/" + employee.getDepartmentId();
        String jsonStr = restTemplate.getForObject(url, String.class);
        ResultMessage<Department> resultMessage = objectMapper.readValue(jsonStr, new TypeReference<ResultMessage<Department>>() {
        });
        Department dept = resultMessage.getData();
        employee.setDepartment(dept);

        return employee;
    }

}
